package com.nkym.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.nkym.common.ErrorCode;

import com.nkym.pojo.entity.User;
import com.nkym.pojo.service.InnerInterfaceInfoService;
import com.nkym.pojo.service.InnerUserService;

import com.nkym.utils.SignUtil;
import com.nkym.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    RedisTemplate<String, Object> redisTemplate;
    @DubboReference
    InnerUserService userService;
    @DubboReference
    InnerInterfaceInfoService interfaceInfoService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders requestHeaders = request.getHeaders();
        String path = request.getPath().value();
        String method = request.getMethodValue();
        String timestamp = requestHeaders.getFirst("timestamp");
        String nonce = requestHeaders.getFirst("nonce");
        String accessKey = requestHeaders.getFirst("accessKey");
        String sign = requestHeaders.getFirst("sign");


        //校验身份，核对请求
        if (timestamp == null || nonce == null || accessKey == null || sign == null) {
            throw new BusinessException(ErrorCode.USER_NOTFOUND);
        }
        //防止Http重放攻击
        Object existNonce = redisTemplate.opsForValue().get(nonce);
        if (existNonce != null) {
            throw new BusinessException(ErrorCode.FORBIDDEN);
        }
        long nowTime = System.currentTimeMillis();
        if (nowTime - Long.parseLong(timestamp) > 5 * 60 * 1000) {
            throw new BusinessException(ErrorCode.FORBIDDEN);
        }
        User user = userService.getUserByAccesskey(accessKey);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOTFOUND);
        }
        boolean validSignature = SignUtil.validSignature(sign, accessKey, user.getSecretKey(), Long.parseLong(timestamp), nonce);
        if (!validSignature) {
            throw new BusinessException(ErrorCode.FORBIDDEN);
        }

        //校验接口
        Integer InterfaceInfoId = interfaceInfoService.getInterfaceInfoId(method, path);
        if (InterfaceInfoId == null) {
            throw new BusinessException(ErrorCode.INTERFACE_EMPTY);
        }
        Integer userId = user.getId();
        //校验是否还有调用次数
        Integer count = interfaceInfoService.hasInvokeTime(userId, InterfaceInfoId);
        if (count == null|| count <= 0  ) {
            throw new BusinessException(ErrorCode.USER_NOTHAVE_INVOKE);
        }


        return handleResponse(exchange, chain, userId, InterfaceInfoId);
    }

    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, Integer userId, Integer interfaceInfoId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. 调用成功，接口调用次数 + 1 invokeCount
                                        try {
                                            postHandle(exchange.getRequest(), exchange.getResponse(), interfaceInfoId, userId);
                                        } catch (Exception e) {
                                            log.error("invokeCount error", e);
                                            throw new BusinessException(ErrorCode.ERROR_CODE);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }

    public void postHandle(ServerHttpRequest request, ServerHttpResponse response, Integer interfaceInfoId, Integer userId) {
        System.out.println(1231231);
        String nonce = request.getHeaders().getFirst("nonce");
        if (nonce == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN);
        }
        if (response.getStatusCode() == HttpStatus.OK) {
            try {
                //调用成功 存入nonce到redis中，防止重放
                redisTemplate.opsForValue().set(nonce, 1, 5, TimeUnit.MINUTES);
                // 接口统计次数+1
                interfaceInfoService.decreaseInvokeTimes(userId, interfaceInfoId);
            } catch (Exception e) {
                throw new BusinessException(ErrorCode.ERROR_CODE);
            }
            //todo 响应日志
        } else {
            log.info("{}", response.getStatusCode());

        }
    }
}